package cn.gp.interceptor;

import cn.gp.common.R;
import cn.gp.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName LoginCheckInterceptor
 * @Description 登陆校验拦截器
 * @Author He_Guoping
 * @Date 2023/5/25 11:45
 * @Version 1.0
 */
@Log4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 1.若为登陆请求，则放行
        String url = req.getRequestURI();
        if(url.contains("login")) {
            log.info("登陆请求需放行");
            return true;
        }

        // 2.判断请求头中是否携带token
        String token = req.getHeader("token");
        if(!StringUtils.hasLength(token)) {
            log.info("token不存在");
            resp.getWriter().write(JSONObject.toJSONString(R.error("not logged in")));
            return false;
        }

        // 3.token解析失败，拦截
        try {
            JwtUtils.parseToken(token);
        } catch(Exception e) {
            log.info("解析token失败");
            resp.getWriter().write(JSONObject.toJSONString(R.error("not logged in")));
            return false;
        }

        // 4.放行
        log.info("token合法");
        return true;
    }
}
